package com.auto.autoapp.base

import android.app.ProgressDialog
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.graphics.toColorInt
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.auto.autoapp.util.toast
import com.auto.autoapp.widgets.SimpleToolbar
import com.google.gson.Gson

abstract class BaseActivity : AppCompatActivity(), IView {


    private var progressDialog: ProgressDialog? = null
    open val gson = Gson()
    override fun showLoading(msg: String?) {
        if (progressDialog == null) {
            progressDialog = ProgressDialog(this)
        }
        progressDialog?.setMessage(msg ?: "加载中")
        if (progressDialog?.isShowing == false) {
            progressDialog?.show()
        }
    }

    override fun hideLoading() {
        progressDialog?.dismiss()
    }

    override fun onDestroy() {
        hideLoading()
        super.onDestroy()
    }

    override fun showToast(msg: String?) {
        if (msg.isNullOrEmpty()) {
            return
        }
        toast(msg, context = this)
    }

    abstract fun provideView(): View
    open fun showToolbar(): Boolean {
        return true
    }

    abstract fun onInit()

    open fun configToolbar(toolbar: SimpleToolbar) {}
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        val contentView = provideView()
        val rootView = if (showToolbar()) {
            val layout = LinearLayoutCompat(this)
            layout.orientation = LinearLayoutCompat.VERTICAL
            val toolbar = SimpleToolbar(this)
            configToolbar(toolbar)
            layout.addView(toolbar)
            val layoutParams =
                LinearLayoutCompat.LayoutParams(
                    LinearLayoutCompat.LayoutParams.MATCH_PARENT,
                    LinearLayoutCompat.LayoutParams.MATCH_PARENT
                )
            layoutParams.weight = 1.0f
            layout.addView(contentView, layoutParams)
            layout
        } else {
            contentView
        }
        rootView.setBackgroundColor("#f5f5f5".toColorInt())
        setContentView(rootView)
        ViewCompat.setOnApplyWindowInsetsListener(rootView) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            val imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
            val imeInsets = insets.getInsets(WindowInsetsCompat.Type.ime())
            val bottomPadding = if (imeVisible) imeInsets.bottom else 0
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, bottomPadding)
            insets
        }
        onInit()
    }


}